package com.example.networkprofiler;
import java.net.*;
import java.security.SecureRandom;
import java.io.*;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
import android.net.TrafficStats;
import android.os.Environment;

import org.apache.commons.io.FileUtils;

public class SpeedTestThreadHttp2 implements Runnable {
	private final String USER_AGENT = "Mozilla/5.0";
	 
	 static AtomicInteger count = null;
	 static long startTime = 0;
	 static long startData = 0;
	 static long endTime = 0;
	 static long endData = 0;
	 String url = "http://www.cs.purdue.edu/homes/jin72/";
	 int thread;
	 File destFile;
		URL obj;
	public SpeedTestThreadHttp2(int i){
		thread = i;
		if(count == null) count = new AtomicInteger(1);
		else {			
			count.getAndAdd(1);
		}		
		url += i + ".txt";
		//url += "1mb.txt";
		//url = "http://download.thinkbroadband.com/5MB.zip";
		String dest= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()+"/"+thread+".txt";
		try{
			obj = new URL(url);
			destFile = new File(dest);
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
	public void run(){
		
		
		try{				
			startTiming();
			FileUtils.copyURLToFile(obj, destFile);
			endTiming();			
		}catch(Exception e){
			e.printStackTrace();
		}
		
	
	}
	
	public synchronized void startTiming(){
		if(count.getAndDecrement() ==1) {
			startData = TrafficStats.getTotalRxBytes();
			startTime=System.currentTimeMillis();
			System.out.println(startData+ " "+startTime);
		}else{
			System.gc();
		}
	}
	
	public synchronized void endTiming(){
		if(count.getAndIncrement() ==0){			
			endTime = System.currentTimeMillis(); 
			endData = TrafficStats.getTotalRxBytes();
			System.out.println(endData+ " "+endTime);
		}
	}
	

}
